package com.org.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil {

	private static Properties p = new Properties();
	private static Connection conn = null;
	private static PreparedStatement ps = null;
	private static ResultSet rs = null;
	private static String url = null;
	private static String user= null;
	private static String pwd = null;



	static {

		try {
			String pathName = "E:/idea-workspace/clothing/src/db.properties";
			p.load(new FileInputStream(pathName));
			url = p.getProperty("url");
			user = p.getProperty("userName");
			pwd = p.getProperty("userPsw");
			Class.forName(p.getProperty("driver"));
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	public static void getConnection() {
			try {
				conn = DriverManager.getConnection(url,user,pwd);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	

	public static boolean insertOrUpdateOrDelete(String sql, Object[] objs) {
		
		getConnection();
		System.out.println("数据库连接成功");
		try {
			 ps = conn.prepareStatement(sql);
			if(objs !=null) {
				
				for(int i = 0; i < objs.length;i++) {
					Object param = objs[i];
					ps.setObject(i+1, param);
				}
			}
			
			int row = ps.executeUpdate();
			if (row > 0) {
				return true;
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			closeConn();
		}
		
		return false;
	}
	
	public static ResultSet select(String sql, Object[] objs) {
		getConnection();
		
		try {
			ps = conn.prepareStatement(sql);
			

			if(objs !=null) {
				
				for(int i = 0; i < objs.length;i++) {
					Object param = objs[i];
					ps.setObject(i+1, param);
				}
			}
			
			rs = ps.executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return rs;
	}
	

	public static void closeConn() {
		try {
			if(rs != null && !rs.isClosed()) {
				rs.close();
			}
			if(ps != null && !ps.isClosed()) {
				ps.close();
			}
			
			if(conn != null && !conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
